import axios from "axios";
import { useUserStore } from "@/store/modules/useUserStore";
import codeMsg from "./errorMsg.js";
import { ElMessage } from "element-plus";
import { useRouter } from "vue-router";
import qs from "qs";

const BASE_URL = import.meta.env.VITE_BASE_URL;

const instance = axios.create({
  baseURL: BASE_URL,
  timeout: 10000,
  paramsSerializer: function (params) {
    return qs.stringify(params, { arrayFormat: "repeat" });
  }
});

// 添加请求拦截器
instance.interceptors.request.use(
  function (config) {
    const userStore = useUserStore();
    config.headers["Authorization"] = "Bearer " + userStore.userToken; // 让每个请求携带自定义token

    return config;
  },
  function (error) {
    console.log(error);
    return Promise.reject(error);
  }
);

//添加响应拦截器
instance.interceptors.response.use(
  function (res) {
    if (res.data.code === 200) {
      return res.data;
    } else {
      return Promise.resolve(res.data);
    }
  },
  function (error) {
    console.log("err " + error);
    let { message } = error;
    if (message == "Network Error") {
      message = "后端接口连接异常";
    } else if (message.includes("timeout")) {
      message = "系统接口请求超时";
    } else if (message.includes("Request failed with status code")) {
      const code = message.substr(message.length - 3);
      if (code === "401") {
        useUserStore().clearUserInfo();
        useRouter().replace({ path: "/Login" });
      }
      message = error.response.data.message || codeMsg[code];
    }
    ElMessage({
      message: message,
      grouping: true,
      plain: true,
      type: "error"
    });
    return Promise.reject(error);
  }
);

export default instance;
